<?php
class Bliss_Media
{
	protected $_contents = '';
	protected $_directory;
	protected $_root;
	protected $_files = array();
	
	public function __construct($request)
	{
		$parts = explode('/', $request);
		$this->_files = explode(',', array_pop($parts));
		$this->_directory = implode('/', $parts);
	}
	
	public function setRoot($root)
	{
		$this->_root = rtrim($root, "/");
		return $this;
	}
	
	public function compile()
	{
		foreach($this->_files as $filename) {
			$dir  = strlen($this->_directory) ? $this->_directory.'/' : '';
			$path = "{$this->_root}/{$dir}{$filename}";
			$file = new Bliss_Media_File($path);
			$this->_contents .= $file->compile();
		}
		
		return $this;
	}
	
	public function output()
	{
		return $this->_contents;
	}
	
	public function display()
	{
		header("Expires: ". gmdate('D, d M Y h:i:s \G\M\T', mktime(date('h'), date('i'), date('s'), date('m'), date('d'), date('Y')+1)));
		header("Cache-Control: cache");
		header("Pragma: cache");
		header("Content-type: ". $this->getMimeType());
		echo $this->output();
		exit;
	}
	
	protected function _compile($path, $ext)
	{
		$contents = '';
		if(is_file($path)) {
			$contents .= file_get_contents($path);
		}
		
		$info = pathinfo($path);
		$dir = $info['dirname'].'/'.$info['filename'];
		if(is_dir($dir)) {
			foreach(new DirectoryIterator($dir) as $item) {
				if($item->isDot()) continue;
				
				$extension = pathinfo($item->getBasename(), PATHINFO_EXTENSION);
				if($item->isFile() && $extension == $ext) {
					$contents .= file_get_contents($item->getPathName());
				} elseif($item->isDir()) {
					$contents .= $this->_compile($item->getPathName(), $ext);
				}
			}
		}
		
		return $contents;
	}
	
	protected function setParams($data)
	{
		foreach($data as $name) {
			$parts = explode(":", $name);
			$this->_params[$parts[0]] = isset($parts[1]) ? $parts[1] : '1';
		}
	}
	
	protected function hasParam($name)
	{
		return isset($this->_params[$name]);
	}
	
	protected function getParam($name, $default=0)
	{
		return $this->hasParam($name) ? $this->_params[$name] : $default;
	}
	
	protected function getMimeType()
	{
		$ext = strtolower(pathinfo($this->_files[0], PATHINFO_EXTENSION));
		switch($ext) {
			case 'css':
				return 'text/css';
				break;
			case 'js':
				return 'text/javascript';
				break;
			case 'jpeg':
			case 'jpg':
				return 'image/jpeg';
				break;
			case 'gif':
				return 'image/gif';
				break;
			case 'png':
				return 'image/png';
				break;
			case 'ico':
				return 'image/x-icon';
				break;
			case 'swf':
				return 'application/x-shockwave-flash';
				break;
			default:
				return 'text/plain';
				break;
		}
	}
}
?>